package com.spsy.pay.config;

import com.spsy.pay.constant.RabbitMqConstantAli;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: Kyrie Irving
 * @Date: 2025/9/26 16:53
 * @Description:
 **/
//@Configuration
public class RabbitmqConfigAli {

    @Bean
    public Queue createQueue1(){
        return new Queue(RabbitMqConstantAli.MQ_NAME,true);
    }

    @Bean
    public DirectExchange createExchange(){
        return new DirectExchange(RabbitMqConstantAli.MQ_EXCHANGE);
    }
    @Bean
    public Binding createBinding(){
        return BindingBuilder.bind(this.createQueue1()).to(this.createExchange()).with(RabbitMqConstantAli.MQ_ROUTING);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        //强制模式: 确保消息能被路由到队列，如果无法路由会触发回退机制
        rabbitTemplate.setMandatory(true);


        //生产者确认
        rabbitTemplate.setConfirmCallback((CorrelationData,ack,cause)->{
            //判断消息是否到达队列
            if (ack){
                System.out.println("消息发送成功"+CorrelationData.getId());
            }else {
                System.out.println("消息发送失败"+cause+"------"+CorrelationData.getId());
            }
        });

        //消息到达交换机但未到达队列
        rabbitTemplate.setReturnsCallback(returnd->{
            System.out.println("错误码："+returnd.getReplyCode());
            System.out.println("原因："+returnd.getReplyText());
            System.out.println("交换机："+returnd.getExchange());
            System.out.println("路由键："+returnd.getRoutingKey());
            System.out.println("消息："+new String(returnd.getMessage().getBody()));
        });

        return rabbitTemplate;

    }

}
